package org.spring.qq_chat_java.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.spring.qq_chat_java.pojo.Result;
import org.spring.qq_chat_java.pojo.User;
import org.spring.qq_chat_java.pojo.uto.loginUTO;
import org.spring.qq_chat_java.service.UserService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class UserController {
    private final UserService userService;

    @GetMapping("/login")
    public Result<loginUTO> login(String account, String password) {

        User user=userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getAccount, account)
                .eq(User::getPassword, password));
        if(user==null){
            return Result.error("用户名或密码错误");
        }
        //随机token
        String token = java.util.UUID.randomUUID().toString();
        return Result.success(new loginUTO(user.getId(),token,user.getUsername(),user.getAvatar()));
    }
    //通过id查询用户
    @GetMapping
    public Result<User> getById(Long id) {

        User user = userService.getById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }


    //新增用户
    @PostMapping("/register")
    public Result<User> add(@RequestBody User user) {
        System.out.println(user);
        if (userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername())) != null) {
            return Result.error("昵称已存在");
        }
        //随机6位整数账号
        user.setAccount(String.valueOf((int)(Math.random()*1000000)));

        userService.save(user);
        return Result.success(user);
    }




}
